package com.abe.libcore.base.http.interceptor

import com.abe.libcore.utils.CommonUtils
import okhttp3.Interceptor
import okhttp3.Protocol
import okhttp3.Response
import java.net.URLDecoder
import java.nio.charset.Charset

class OKHttpInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain?): Response? {
        val request = chain!!.request()
        try {
            val connection = chain.connection()
            val protocol = if (connection != null) connection.protocol() else Protocol.HTTP_1_1
            CommonUtils.log(divider)
            val requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol
            CommonUtils.log(requestStartMessage)
            val response = chain.proceed(request)
            val responseBody = response.body()
            val contentLength = responseBody!!.contentLength()
            var bodyValue = "NONE"
            val source = responseBody.source()
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer()
            val empty: Long = 0
            if (contentLength != empty) {
                try {
                    bodyValue = URLDecoder.decode(buffer.clone().readString(UTF8), "UTF-8")
                } catch (e: Exception) {
                    e.printStackTrace()
                    CommonUtils.log("bodyValue-exception:" + e.message)
                }
            }
            CommonUtils.log(bodyValue)
            CommonUtils.log(divider)
            return response
        } catch (e: Exception) {
            e.printStackTrace()
            CommonUtils.log("all-exception(OKHttpInterceptor):" + e.message)
            return chain.proceed(request.newBuilder().build())
        }
    }

    private val UTF8: Charset = Charset.forName("UTF-8")
    private val divider: String = "********************************************************************************************************************************"
}